"""
f2 均线偏离度因子
与均线的偏离度（多个周期） （10分钟、20分钟均线用来衡量当前价格的偏离度        更大周期的均线用来衡量大周期是否逆市） （就是不同周期的不同参数的乖离率因子)
1分钟 X分别取值6 12 24 48 96
数学公式：(close-均值（close,x） )*100/均值（close,x）  （归一化处理 ）
"""
import pandas as pd
import rqdatac as rq
from ..utility import make_domaint_time_dict
from datetime import timedelta


def self_get_factor_df(sec_id):
    symbol_time_dict = make_domaint_time_dict(sec_id)
    result_df = {}
    prices_df = {}
    for symbol, time_dict in symbol_time_dict.items():
        prices = rq.get_price(symbol, start_date="20220801", end_date="20231116", frequency="1m",
                              fields=["close", "high", "low"], expect_df=False)
        prices.index -= timedelta(minutes=1)
        prices["atr"] = ((prices["high"] - prices["low"]) / prices["low"]).rolling(1000).mean()
        symbol_df = pd.DataFrame()
        for window in [6, 12, 24, 48, 96]:
            prices[f"ma_{window}"] = prices["close"].rolling(window).mean()
            prices[f"deviation_{window}"] = (prices["close"] - prices[f"ma_{window}"]) / prices[f"ma_{window}"]
            prices[f"ma_deviation_{window}"] = prices[f"deviation_{window}"] / prices["atr"]   # atr归一化
            symbol_df[f"ma_deviation_{window}"] = prices[f"ma_deviation_{window}"]
        prices = prices[time_dict["start"]: time_dict["last"]]
        symbol_df = symbol_df[time_dict["start"]: time_dict["last"]]
        symbol_df["symbol"] = symbol
        prices["symbol"] = symbol
        result_df[symbol] = symbol_df
        prices_df[symbol] = prices
    return pd.concat(list(result_df.values())), pd.concat(list(prices_df.values()))


def get_factor_df(sec_id, prices):
    print(sec_id,  __file__)
    atr = ((prices["high"] - prices["low"]) / prices["low"]).rolling(1000).mean()
    for window in [6, 12, 24, 48, 96]:
        ma = prices["close"].rolling(window).mean()
        deviation = (prices["close"] - ma) / ma
        prices[f"ma_deviation_{window}"] = deviation / atr   # atr归一化
    return prices


if __name__ == "__main__":
    if not rq.initialized():
        rq.init("13570866213", "39314656")
